import { Inject, Injectable } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
import { PrismaService } from 'src/prisma.service';
import { Article, ArticleInclude } from './entities/article.entity';
import { plainToClass, plainToInstance } from 'class-transformer';
import { ArticleDetailDto } from './dto/article-detail.dto';

@Injectable()
export class ArticleService {
  @Inject()
  prismaService: PrismaService;

  async create(
    createArticleDto: CreateArticleDto,
    userId: number,
  ): Promise<Article> {
    const res = await this.prismaService.article.create({
      data: {
        title: createArticleDto.title,
        content: createArticleDto.content,
        userId,
      },
      include: ArticleInclude,
    });
    return plainToClass(Article, res);
  }

  async findAll(): Promise<Article[]> {
    const res = await this.prismaService.article.findMany({
      include: ArticleInclude,
    });
    return plainToInstance(Article, res);
  }

  async findOne(id: number, userId?: number): Promise<ArticleDetailDto> {
    const res = await this.prismaService.article.findUniqueOrThrow({
      where: { id },
      include: ArticleInclude,
    });

    const isLike = res.likes.some((el) => {
      return el.userId === userId;
    });
    return plainToInstance(ArticleDetailDto, { ...res, isLike });
  }

  async update(
    id: number,
    updateArticleDto: UpdateArticleDto,
  ): Promise<Article> {
    const res = await this.prismaService.article.update({
      data: updateArticleDto,
      where: { id },
      include: ArticleInclude,
    });
    return plainToInstance(Article, res);
  }

  async remove(id: number) {
    await this.prismaService.comment.deleteMany({
      where: { articleId: id },
    });
    await this.prismaService.articleLike.deleteMany({
      where: { articleId: id },
    });
    await this.prismaService.articleView.deleteMany({
      where: { articleId: id },
    });
    await this.prismaService.article.delete({
      where: { id },
    });
    const res = '删除成功';
    return res;
  }
}
